import { useState, useEffect, useCallback } from "react";

import API from '../API';

// Helpers
import { isPersistedState } from "../helpers";


export const useMovieFetch = movieId => {
    const [state, setState] = useState({});
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(false);

    const fetchMovie = useCallback(async () => {
        try {
            setLoading(true);
            setError(false);

            const movie = await API.fetchMovie(movieId);
            const credits = await API.fetchCredits(movieId);

            const directors = credits.crew.filter(
                member => member.job === 'Director'
            )
            const res = {
                ...movie,
                actors: credits.cast,
                directors
            };
            await setState(res);

            setLoading(false);
        } catch (error) {
            setLoading(false);
            setError(true);
        }
    }, [movieId])

    useEffect(() => {
        const sessionState = isPersistedState(movieId);
        if (sessionState) {
            setState(sessionState);
            setLoading(false);
            return;
        }

        fetchMovie();
    }, [movieId]);

    // Write to sessionStoreage
    useEffect(() => {
        sessionStorage.setItem(movieId, JSON.stringify(state));
    }, [movieId, state]);

    return {state, loading, error}
}